import librosa.display
import os
from moviepy.editor import VideoFileClip
import main_beat_detector
import ffmpeg

def create_directory_if_not_exists(directory):
    # 检查文件夹是否存在，如果不存在则创建
    if not os.path.exists(directory):
        os.makedirs(directory)

if __name__ == '__main__':
    fileName = "video/UID75352309265_小马漫漫/video/2024-02-06 17.38.10-小马漫漫-L@w.fB 好喜欢红色呀 # 小红裙 # 浅跳一下"
    input_mp4_file = f"E:/{fileName}.mp4"

    start_index = fileName.find('video/') + len('video/')
    end_index = fileName.find('/video/')

    uid_author_name = fileName[start_index:end_index]
    fileName = os.path.basename(input_mp4_file).split(".mp4")[0]


    # fileName = "2023-12-30 21.15.31-呼呼-0326 j@c.nq 扣6吸走前任财运# 御姐"
    # UIDAuthor = "UID3510099090342622_呼呼"
    # # 输入的MP4文件名
    # input_mp4_file = f"E:/video/{UIDAuthor}/video/{fileName}.mp4"

    # 输出的MP3文件名
    musicDir = 'music'
    output_mp3_file = f"{musicDir}/{fileName}.mp3"
    # beat_dir = 'beatClipCache'
    output_folder = 'beatClip'

    threshold = 2
    main_beat_detector.mp4_to_mp3(musicDir, input_mp4_file, output_mp3_file)

    # 提取音频数组
    beat_times = main_beat_detector.music_beat_time(output_mp3_file)
    # 打开文件并写入数组元素
    last_time = 0
    clip_times = []
    for (index, beat_time) in enumerate(beat_times):
        if not beat_time:
            break
        beat_time = float(beat_time)
        if beat_time-last_time > threshold or index == (len(beat_times) - 1):
            clip_times.append(beat_time)
            last_time = beat_time
    print(clip_times)

    # 将时长转换为毫秒并转为字符串格式
    start_times = clip_times

    output_folder = f'{output_folder}/{uid_author_name}/{fileName}'
    create_directory_if_not_exists(output_folder)
    # 使用FFmpeg分割视频
    # 遍历时间点数组，分割视频
    for i, split_point in enumerate(start_times):
        start_time = 0 if i == 0 else start_times[i - 1]
        end_time = split_point
        print(f"开始时间：{start_time}，结束时间{end_time}")
        # 使用ffmpeg进行分割
        ffmpeg.input(input_mp4_file, ss=start_time, to=end_time)\
            .output(f'{output_folder}/{fileName}-Scene-9{str(i + 1).zfill(2)}.mp4')\
            .run(overwrite_output=True)

    print("视频分割完成。")
